package com.appspot.battlerafts.servlets.game;

import com.appspot.battlerafts.classes.Game;
import com.appspot.battlerafts.jsons.GameStartJSON;
import com.appspot.battlerafts.utils.PMF;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.appspot.battlerafts.utils.Util.returnSuccess;

/**
 * Created by IntelliJ IDEA.
 * User: Tonis
 * Date: 21.03.12
 * Time: 17:12
 * To change this template use File | Settings | File Templates.
 */

public class InitGame extends HttpServlet {

    private static final Logger log = Logger.getLogger(InitGame.class.getName());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        log.info("TIME: " + request.getParameter("data"));
        GameStartJSON gameStartJSON = gson.fromJson(request.getParameter("data"), GameStartJSON.class);
        log.info(gameStartJSON.toString());
        log.setLevel(Level.INFO);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            Game game = new Game(gameStartJSON.gameID, gameStartJSON.initatorID, gameStartJSON.nrOfPlayers, gameStartJSON.itendedPlayers, gameStartJSON.startTime);
            pm.makePersistent(game);
        }finally {
            pm.close();
        }

        returnSuccess(response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}
